package com.stylefeng.guns.modular.pay.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.stylefeng.guns.core.util.HttpResp;
import com.stylefeng.guns.modular.pay.dao.NotifyRecordLogMapper;
import com.stylefeng.guns.modular.pay.dao.NotifyRecordMapper;
import com.stylefeng.guns.modular.pay.model.NotifyRecord;
import com.stylefeng.guns.modular.pay.model.NotifyRecordLog;
import com.stylefeng.guns.modular.pay.model.Trans;
import com.stylefeng.guns.modular.pay.service.INotifyRecordService;

/**
 * <p>
 * 通知记录表 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-08-24
 */
@Service
public class NotifyRecordServiceImpl extends ServiceImpl<NotifyRecordMapper, NotifyRecord> implements INotifyRecordService {
	@Autowired
	private NotifyRecordMapper notifyRecordMapper;
	@Autowired
	private NotifyRecordLogMapper notifyRecordLogMapper;
	
	@Override
	public List<NotifyRecord> list(Page<NotifyRecord> page, NotifyRecord notifyRecord) {
		// TODO Auto-generated method stub
		return notifyRecordMapper.list(page,notifyRecord);
	}

	@Transactional
	@Override
	public void notifyLog(Trans trans, String createLinkString, HttpResp notifyRes) {
		NotifyRecordLog log = new NotifyRecordLog();
		log.setCreateTime(new Date());
		log.setHttpStatus(notifyRes.getStatus());
		log.setMerchantNo(trans.getMchNo());
		log.setNotifyType(0);
		log.setOutOrderNo(trans.getOrderCode());
		log.setPlatTradeNo(trans.getPlatOrderCode());
		log.setRequest(createLinkString);
		if(notifyRes!=null&&!Strings.isNullOrEmpty(notifyRes.getResMsg())){
			if(notifyRes.getResMsg().length()>600){
				log.setResponse(notifyRes.getResMsg().substring(0, 100));
			}else{
				log.setResponse(notifyRes.getResMsg());
			}
		}
		notifyRecordLogMapper.insert(log);
		NotifyRecord record = notifyRecordMapper.findByPlatTradeNo(trans.getPlatOrderCode());
		if(record!=null){
			if(notifyRes!=null && "success".equals(notifyRes.getResMsg())){
				record.setStatus(1);
			}else{
				int count = record.getNotifyFailTimes()==null?0:record.getNotifyFailTimes();
				record.setNotifyFailTimes(count+1);
			}
			notifyRecordMapper.updateById(record);
		}
	}

}
